package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.base.utils.StringUtils;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.oa.core.entity.com.ChatLog;
import com.fz.us.oa.core.entity.com.Friend;
import com.fz.us.oa.core.service.com.ChatLogService;
import com.fz.us.oa.core.service.com.FriendService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/6.
 */
@Controller
@RequestMapping(value = "/com/friend")
public class FriendController extends BaseController {
    private static final long serialVersionUID = 2222499116439278925L;

    @Autowired
    private FriendService friendService;
    @Autowired
    private UserService userService;
    @Autowired
    private ChatLogService chatLogService;

    private static String AccountSid="8aaf07085c9b999c015caaa5ac290975";
    private static String AccountToken="efcb23f49bf34f51ac308967764a390d";
    private static String AppId="8aaf07085c9b999c015caaa8ba8e0987";
    private static String ServerIP="app.cloopen.com";
    private static String ServerPort="8883";
    private static String SoftVersion="2013-12-26";
    private static String timestamp="";

    /**
     * 测试
     */
    @RequestMapping(value= "ceshi",method = RequestMethod.POST)
    public void ceshi(){
        System.out.println("###################");
    }

    /**
     * 添加好友
     */
    @RequestMapping(value = "add",method = RequestMethod.POST)
    public Object save(@CurrentUser User user, String friendId){
        Friend friend1=friendService.getFriend(user,userService.get(friendId));
        if(friend1==null){
            Friend friend=new Friend();
            friend.setOwn(user);
            friend.setFriend(userService.get(friendId));
            friend.setName(user.getName());
            friendService.save(friend);
            return ajaxJson(resultService.success("添加成功"));
        }else{
            return ajaxJson(resultService.fail("添加失败"));
        }
    }

    /**
     * 删除好友
     */
    @RequestMapping(value= "del",method = RequestMethod.POST)
    public Object delete(@CurrentUser User user, String friendId){
        Friend friend=friendService.getFriend(user,userService.get(friendId));
        friendService.delete(friend);
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("stats", 200);
        return ajaxJson(map);
    }

    /**
     * 获取当前登录人的好友列表和聊天记录
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object list(@CurrentUser User user) throws UnsupportedEncodingException {
        Map<String, Object> data=new HashMap<String, Object>();
        List<JSONObject> list=new ArrayList<JSONObject>();
        Map<String, Object> friendMap;
        List<JSONObject> chatLogList1;
        List<Friend> friendList=friendService.getFriendList(user);
        for(Friend friend:friendList){
            friendMap=new HashMap<String, Object>();
            User myFriend=friend.getFriend();
            friendMap.put("name",myFriend.getName());
            friendMap.put("id", myFriend.getId());

            //获取此与好友的聊天记录
            chatLogList1=new ArrayList<JSONObject>();
            Map<String, Object> chatLogMap;
            List<ChatLog> chatLogList=chatLogService.findChatLogFriend(user, myFriend);
            for(ChatLog c:chatLogList){
                chatLogMap=new HashMap<String, Object>();
                chatLogMap.put("sender",c.getSender().getName());
                chatLogMap.put("senderId",c.getSender().getId());
                chatLogMap.put("chatType",StringUtils.isNotEmpty(c.getChatType())?c.getChatType():"");
                chatLogMap.put("receiver", userService.get(c.getReceiverId()).getName());
                chatLogMap.put("content", StringUtils.isNotEmpty(c.getContent())?c.getContent():"");
                chatLogMap.put("fileName", StringUtils.isNotEmpty(c.getFileName())?c.getFileName():"");
                chatLogMap.put("fileSize", StringUtils.isNotEmpty(c.getFileSize())?c.getFileSize():"");
                chatLogMap.put("fileAddress", StringUtils.isNotEmpty(c.getFileAddress())?c.getFileAddress():"");
                chatLogMap.put("date", DataUtil.DateTimeToString(c.getCreateTime()));
                chatLogMap.put("msgId",StringUtils.isNotEmpty(c.getMsgId())?c.getMsgId():"");
                chatLogList1.add(JSONObject.fromObject(chatLogMap));
            }
            friendMap.put("chatLog",chatLogList1);

            list.add(JSONObject.fromObject(friendMap));
        }
        data.put("friendList", list);
        return ajaxJson(JSONObject.fromObject(data));
    }

    /**
     * 添加一条聊天记录
     */
    @RequestMapping(value = "addChatLog", method = RequestMethod.POST)
    public Object addChatLog(@CurrentUser User user, String friendId, String content, String chatType, String fileName, String fileSize, String fileAddress, String msgId){
        ChatLog chatLog=new ChatLog();
        chatLog.setSender(user);
        chatLog.setReceiverId(friendId);
        chatLog.setChatType(chatType);
        chatLog.setContent(content);
        chatLog.setName("X﹏X");
        chatLog.setFileName(fileName);
        chatLog.setFileSize(fileSize);
        chatLog.setFileAddress(fileAddress);
        chatLog.setMsgId(msgId);
        return ajaxJson(chatLogService.saveEntity(chatLog));
    }

    /**
     * 获取与一个好友的30条聊天记录
     */
    @RequestMapping(value = "getChatLog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object getChatLog(@CurrentUser User user, String friendId){
        User friend=userService.get(friendId);
        List<ChatLog> chatLogList=chatLogService.findChatLogFriend(user, friend);
        List<JSONObject> list=new ArrayList<JSONObject>();
        Map<String,Object> bigChatLog=new HashMap<String, Object>();
        Map<String,Object> map;
        for(ChatLog c:chatLogList){
            map=new HashMap<String, Object>();
            map.put("sender",c.getSender().getName());
            map.put("senderId",c.getSender().getId());
            map.put("receiver",userService.get(c.getReceiverId()).getName());
            map.put("content",c.getContent());
            map.put("date", DataUtil.DateTimeToString(c.getCreateTime()));
            list.add(JSONObject.fromObject(map));
        }
        bigChatLog.put("chatLog", list);
        return ajaxJson(JSONObject.fromObject(bigChatLog));
    }

    /**
     * 获取群组的聊天记录
     * @return
     */
    @RequestMapping(value = "getGroupChatLog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object getGroupChatLog(String groupIds){
        List<JSONObject> list=new ArrayList<JSONObject>();
        Map<String, Object> chatLog=new HashMap<String, Object>();
        Map<String, Object> map;
        for(String groupId:groupIds.split(",")){
            List<ChatLog> chatLogList=chatLogService.findGroupChatLog(groupId);
            for(ChatLog c:chatLogList){
                map=new HashMap<String, Object>();
                map.put("sender",c.getSender().getName());
                map.put("senderId",c.getSender().getId());
                map.put("chatType",StringUtils.isNotEmpty(c.getChatType())?c.getChatType():"");
                map.put("receiver", StringUtils.isNotEmpty(c.getReceiverId())?c.getReceiverId():"");
                map.put("content", StringUtils.isNotEmpty(c.getContent())?c.getContent():"");
                map.put("fileName", StringUtils.isNotEmpty(c.getFileName())?c.getFileName():"");
                map.put("fileSize", StringUtils.isNotEmpty(c.getFileSize())?c.getFileSize():"");
                map.put("fileAddress", StringUtils.isNotEmpty(c.getFileAddress())?c.getFileAddress():"");
                map.put("date", DataUtil.DateTimeToString(c.getCreateTime()));
                map.put("msgId",StringUtils.isNotEmpty(c.getMsgId())?c.getMsgId():"");
                list.add(JSONObject.fromObject(map));
            }
        }
        chatLog.put("chatLog", list);
        return ajaxJson(JSONObject.fromObject(chatLog));
    }


    /**
     * 服务端开发
     * @param url
     * @param param
     * @return
     */
    public Object sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            //生成auth
            String src = AccountSid + ":" + timestamp;
            String auth = new sun.misc.BASE64Encoder().encode( src.getBytes() );
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Accept", "application/xml");
//            conn.setRequestProperty("Connection", "close");
            conn.setRequestProperty("Content-type","application/xml;charset=utf-8");
            conn.setRequestProperty("Authorization",auth);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
//            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
//            String iso = new String(result.getBytes("UTF-8"),"ISO-8859-1");
//            result = new String(iso.getBytes("ISO-8859-1"),"UTF-8");
//            result = new String(result.getBytes("gbk"), "utf-8");
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        System.out.println(result);
        return ajaxText(result);
    }


    @RequestMapping(value = "groupInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object groupInfo(){
        //获取系统时间
        String other="8a8a8b9a5c0b9a36015c0b9a4af60001";
        String belong="gg8020566912";
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        timestamp=df.format(new Date());
        //生成sig
        String signature="";
        String sig = AccountSid + AccountToken + timestamp;
        try {
            signature = md5Digest(sig);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //拼接请求包体
        String requsetbody = "";

        StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><Request>");
        sb.append("<appId>").append(AppId).append("</appId>");
        sb.append("<timeType>").append("day").append("</timeType>");
//        sb.append("<other>").append(other).append("</other>");
//        sb.append("<groupId>").append(belong).append("</groupId>");
        sb.append("</Request>").toString();
        requsetbody = sb.toString();
        String url= "https://"+ServerIP+":"+ServerPort+"/"+SoftVersion+"/Accounts/"+AccountSid+"/IM/MsgRecordsNew?sig="+signature;
        System.out.println(sb);
        System.out.println(url);
        return sendPost(url,requsetbody);

    }

    //MD5加密
    public static String md5Digest(String src) throws NoSuchAlgorithmException, UnsupportedEncodingException
    {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] b = md.digest(src.getBytes("utf-8"));
        return byte2HexStr(b);
    }
    private static String byte2HexStr(byte[] b)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < b.length; ++i) {
            String s = Integer.toHexString(b[i] & 0xFF);
            if (s.length() == 1)
                sb.append("0");

            sb.append(s.toUpperCase());
        }
        return sb.toString();
    }


}
